import OSS from 'ali-oss'

const region = "oss-cn-shenzhen.aliyuncs"
const accessKeyId = "LTAI5tEewCaBy7zsdcL6GmVT"
const accessKeySecret = "ZNVPLxgMYGa7CZsghYOVnyOyyJOGFv"
const bucket = "hncxsk"
const urlPrefix = "img.cscxsk.cn"
const  fileHost="upload";// 目标文件夹
import { Message } from 'element-ui';
let client = new OSS({
  region : region,
  accessKeyId : accessKeyId,
  accessKeySecret : accessKeySecret,
  bucket : bucket
});
const CooOss = function(file){
  if(this instanceof CooOss){
    let objectKey = file.lastModified+'_'+file.name;
    return new Promise((resolve,reject) => {
      client.multipartUpload(objectKey, file).then(result =>  {
        resolve({
          code : 0,
          objectKey : objectKey,
          url : this.getOssFileUrl(objectKey),
          msg : "ok"
        });
      }).catch(err => {
        console.error('上传出错了');
        Message.error('上传出错了');
        reject({code : -1 , url : "", objectKey : "", msg : "上传出错了"});
      });
    })
  }
  else{
    return new CooOss(file);
  }
};

CooOss.prototype.getOssFileUrl = obecjtKey => {
  if(!obecjtKey) return  new Error("object key 必须传");
  return "https://" +urlPrefix + obecjtKey;
  // return "https://" + bucket + "." + region + ".aliyuncs.com/" + obecjtKey;
}

const downloadFile = function (key) {
  console.log(key)
  let url = client.signatureUrl(key);
  let Img = new Image(), dataURL = '';
  let fileName = key.substring(key.indexOf('_')+1);
  Img.src = url;
  Img.setAttribute("crossOrigin", 'Anonymous');
  Img.onload = function () {
    let canvas = document.createElement("canvas"),
      width = Img.width,
      height = Img.height;
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(Img, 0, 0, width, height);
    dataURL = canvas.toDataURL('image/png' );
    let eleLink = document.createElement('a');
    eleLink.download = fileName;
    eleLink.style.display = 'none';
    eleLink.href = dataURL;
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  };
}

export default {
  install(Vue){
    Vue.prototype.Oss = {
      uploadFile : CooOss,
      downloadFile : downloadFile
    };
  }
};




